package com.compass.mobile.network.manager


import CompassAppHelper
import LogUtil
import NetworkUtil
import com.compass.mobile.framework.constant.BASE_URL
import com.compass.mobile.network.error.ERROR
import com.compass.mobile.network.error.NoNetWorkException
import com.compass.mobile.network.interceptor.HeaderInterceptor
import com.compass.mobile.network.interceptor.PublicParameterInterceptor
import com.compass.mobile.network.interceptor.TokenInterceptor
import okhttp3.ConnectionSpec
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.TlsVersion
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager


/**
 *
 * @desc  网络请求管理类
 */
object HttpManager {
    private val mRetrofit: Retrofit


    //创建一个信任所有证书的 TrustManager
    private val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        @Throws(CertificateException::class)
        override fun checkClientTrusted(
            chain: Array<java.security.cert.X509Certificate>,
            authType: String
        ) {
            // Do not check client certificates.
        }

        @Throws(CertificateException::class)
        override fun checkServerTrusted(
            chain: Array<java.security.cert.X509Certificate>,
            authType: String
        ) {
            // Do not check server certificates.
        }

        override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
            return arrayOf()
        }
    })
    private val sslContext = SSLContext.getInstance("SSL").apply {
        init(null, trustAllCerts, SecureRandom())
    }
    private val sslSocketFactory = sslContext.socketFactory

    init {
        mRetrofit = Retrofit.Builder()
            .client(initOkHttpClient())
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    /**
     * 获取 apiService
     */
    fun <T> create(apiService: Class<T>): T {
        return mRetrofit.create(apiService)
    }


    /**
     * 初始化OkHttp
     */
    private fun initOkHttpClient(): OkHttpClient {


        val build = OkHttpClient.Builder()

            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)

            .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
            .hostnameVerifier { _, _ -> true }

        // 添加参数拦截器
        val interceptors = mutableListOf<Interceptor>()
        build.addInterceptor(HeaderInterceptor())// 头信息拦截器
        build.addInterceptor(PublicParameterInterceptor())//公共参数
        build.addInterceptor(TokenInterceptor())//token拦截器


        //日志拦截器
        val logInterceptor = HttpLoggingInterceptor { message: String ->
            if (CompassAppHelper.isDebug()) {
                LogUtil.d("http_data:$message")

            }
        }
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        build.addInterceptor(logInterceptor)
        //网络状态拦截
        build.addInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                if (NetworkUtil.isConnected(CompassAppHelper.getApplication())) {
                    val request = chain.request()
                    return chain.proceed(request)
                } else {
                    throw NoNetWorkException(ERROR.NETWORD_ERROR)
                }
            }
        })
        return build.build()
    }
}